package com.atguigu.gulimall.seckill.scheduled;

import com.atguigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * 秒杀商品上架
 * 每天晚上3点，上架最近需要秒杀的商品
 * 当天 00:00:00 - 23:59:59
 * 明天 00:00:00 - 23:59:59
 * 后天 00:00:00 - 23:59:59
 *
 * @author gcq
 * @Create 2021-01-08
 */
@Slf4j
@Service
@EnableScheduling // 开启秒杀任务
public class SeckillScheduled {

    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;

    private static final String upload_stock = "seckill:upload:lock";

    /**
     * 扫描三天内的商品并将再指定时间内的商品进行上架
     */
//    @Scheduled(cron = "*/3 * * * * ?")
    @Scheduled(cron = "0/10 * * * * ? ") // 每10秒执行一次
    public void uploadSeckillSkuLatest3Days() {
        /**
         * 整个过程一定要有锁
         *      保证原子性，防止别人获取到我的一个执行状态
         */
        RLock lock = redissonClient.getLock(upload_stock);
        lock.lock();
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        log.info("订单任务执行");
    }
}